package com.code2roc.jarmanage.servlet.depoly;

import com.code2roc.jarmanage.db.ProjectDB;
import com.code2roc.jarmanage.model.ProjectDO;
import com.code2roc.jarmanage.model.Result;
import com.code2roc.jarmanage.util.CommonUtil;
import com.code2roc.jarmanage.util.ConfigUtil;
import com.code2roc.jarmanage.util.ConvertUtil;
import com.code2roc.jarmanage.util.LogUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.util.*;

public class GetBackUpListServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Result result = Result.okResult();
        HashMap paramMap = CommonUtil.getParamMap(req);
        String projectID = ConvertUtil.convert2String(paramMap.get("projectID"));
        List<String> backUpList = new ArrayList<>();
        ProjectDO entity = ProjectDB.selectOne(projectID);
        String depolyPath = entity.getJarPackagePath();
        File deployDir = new File(depolyPath);
        List<File> backUpFileList = Arrays.asList(deployDir.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                return name.startsWith("backup-") && name.endsWith(".jar");
            }
        }));
        backUpFileList.sort(new Comparator<File>() {
            @Override
            public int compare(File o1, File o2) {
                int result = 1;
                try {
                    BasicFileAttributes fileInfo1 = Files.readAttributes(Paths.get(o1.getAbsolutePath()), BasicFileAttributes.class);
                    BasicFileAttributes fileInfo2 = Files.readAttributes(Paths.get(o2.getAbsolutePath()), BasicFileAttributes.class);
                    FileTime fileTime1 = fileInfo1.creationTime();
                    FileTime fileTime2 = fileInfo2.creationTime();
                    result = fileTime2.compareTo(fileTime1);
                } catch (Exception e) {
                    LogUtil.error(e);
                }
                return result;
            }
        });
        for (File file:backUpFileList) {
            backUpList.add(file.getName());
        }
        result.add("obj", backUpList);
        result.add("backupcount",ConvertUtil.convert2Int(ConfigUtil.getConfigValue("backupcount")));
        resp.getWriter().println(result.toString());
    }
}
